﻿using System;
using System.Web;

namespace Smart.Web.Mobile
{
    /// <summary>
    /// 
    /// </summary>
    public class MobileContext
    {
        private Carrier carrier;
        private CarrierSettings carrierSettings;

        /// <summary>
        /// 
        /// </summary>
        public bool IsMobile
        {
            get { return Carrier != Carrier.Other; }
        }

        /// <summary>
        /// 
        /// </summary>
        public Carrier Carrier
        {
            get { return this.carrier; }
        }

        /// <summary>
        /// 
        /// </summary>
        public CarrierSettings CarrierSettings
        {
            get { return this.carrierSettings; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="ua"></param>
        /// <param name="mobileSettings"></param>
        public void Initialize(string ua, MobileSettings mobileSettings)
        {
            this.carrier = Carrier.Other;

            foreach( CarrierMatchingRule rule in mobileSettings.MatchingRules )
            {
                if( !String.IsNullOrEmpty( rule.Contains ) )
                {
                    if( ua.Contains( rule.Contains ) )
                    {
                        this.carrier = rule.Carrier;
                        break;
                    }
                }
            }

            this.carrierSettings = mobileSettings.CarrierSettings[ this.carrier ];
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class ThreadMobileContext
    {
        [ThreadStatic]
        private static MobileContext current;

        /// <summary>
        /// 
        /// </summary>
        public static MobileContext Current
        {
            get
            {
                if( current == null )
                {
                    current = new MobileContext();
                }

                return current;
            }
        }

    }

    /// <summary>
    /// 
    /// </summary>
    public class WebMobileContext
    {
        private const string CONTEXT_NAME = "__MobileContext";

        /// <summary>
        /// 
        /// </summary>
        public static MobileContext Current
        {
            get
            {
                if( HttpContext.Current == null )
                {
                    throw new InvalidOperationException( "HttpContext.Current is null." );
                }

                MobileContext context = (MobileContext)HttpContext.Current.Items[ CONTEXT_NAME ];
                if( context == null )
                {
                    context = new MobileContext();
                    HttpContext.Current.Items[ CONTEXT_NAME ] = context;
                }

                return context;
            }
        }
    }
}
